<?php
namespace Mapi\Controller;
use Mapi\Controller\BaseController;
use Think\Exception;

class LiveController extends BaseController {

	public function __construct() {
		parent::__construct();
	}

	/**
	 * 添加申请直播
	 */
	public function addApplyInfo() {
		apigetpost();
		if(IS_POST) {
			$model = D('Live');

			$dataGet['title'] = I('post.title');
			$user_ids = I('post.user_ids', ''); // 直播人ID
			$dataGet['start_time'] = strtotime(I('post.start_time'));
			$dataGet['address'] = I('post.address');
			$dataGet['intro'] = I('post.intro');
			$dataGet['apply_id'] = $this->uid; // 申请人ID
			$group = date('YmdHis') . '_' . $this->uid . '_' . uniqid(); // 祖名

			$user_ids = $user_ids ? explode(',', $user_ids) : array();

			if(in_array($this->uid, $user_ids)) {
				$key = array_search($this->uid, $user_ids); 
				unset($user_ids[$key]);
			}

			$user_ids[] = $this->uid;
			$user_ids = array_unique($user_ids); // 去重

			$channelres=M('UserInfo')->alias('ui')
			->join('__CHANNEL__ c on ui.userchannel=c.chid')
			->where(array('ui.uid' => $this->uid))->find();
			$dataGet['column_id'] = $channelres['userchannel'];
			$dataGet['create_time'] = time();
			$dataGet['update_time'] = time();
			$dataGet['rand'] = rand(6600, 6800);

			if($model->create($dataGet)) {
				try {
					M()->startTrans();
					if($user_ids) {
						foreach($user_ids as $k => $id) {
							$dataGet['user_id'] = $id;
							$dataGet['apply_id'] = $this->uid;
							$dataGet['group_id'] = $group;
							// $dataGet['url'] = authAliyun('rtmp://video-center.alivecdn.com/jw/' . $group . '_' . $id . '?vhost=jwlive.appwuhan.com');
							// $dataGet['url'] = 'rtmp://video-center.alivecdn.com/jw/' . $group . '_' . $id . '?vhost=jwlive.appwuhan.com';
							// $dataGet['bo_url'] = 'rtmp://jwlive.appwuhan.com/jw/' . $group . '_' . $id;
							$dataGet['group_num'] = implode(',', array_reverse($user_ids));

							$tmp[$k]['id'] = $id;
							$tmp[$k]['stream'] = $group . '_' . $id;

							liveStatus(2, $tmp, -1);

							$res = $model->add($dataGet);
							if(!$res)
								throw new \Exception('服务器异常');
						}

						$relation = unserialize($channelres['relation']);
						$uidList = array();
						if(in_array($this->uid, $relation[0])) {
							foreach ($relation[0] as $key => $value) {
								if($value != $this->uid)
									$uidList[] = $value;
							}
						} else {
							$uidList = $relation[0];
						}

						$trans=json_encode(array('pushCode'=>300,'objectId'=>$res,'userId'=>0));
						sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>$channelres['realname'] . '提交直播《' . $dataGet['title'] . '》申请，请审核！','trans'=>$trans));						


					} else {
						throw new \Exception('申请失败，请重试');
					}

					M()->commit();

					$message['resultCode'] = 0;
					$message['message'] = '申请成功';

				} catch (\Exception $e) {
					M()->rollback();
					$message['resultCode'] = 1;
					$message['message'] = $e->getMessage();
				}

			} else {
				$message['resultCode'] = 1;
				$message['message'] = $model->getError();
			}

		} else {
			$message['resultCode'] = 1;
			$message['message'] = '非法请求';
		}

		$this->ajaxReturn($message);
	}

	/**
	 * 获取直播列表
	 * @return [type] [description]
	 */
	public function getLiveList() {
		apigetpost();

		$pageSize = I('get.pageSize', 10);
		C('VAR_PAGE', 'page');

		$channel = M('Channel')->field('chid, relation')->select();
		$chids = array();
		foreach($channel as $val) {
			$val['relation'] && $val['relation'] = unserialize($val['relation']);
			if(isset($val['relation'][0]) && !empty($val['relation'][0])) {
				if(in_array($this->uid, $val['relation'][0])) {
					$chids[] = $val['chid'];
				}
			}
		}

		if(empty($chids)) {
			$map['user_id'] = $this->uid;
			$map['v_status'] = array('NEQ', -1);
			$model = M('Live');
			$total = $model->where($map)->group('group_id')->count();
			$page = new \Think\Page($total, $pageSize);
			$list = $model->field('id, start_time,v_status,z_status,user_id,apply_id,address,title,group_id,group_num as live_user_num,is_direction')->where($map)->order('start_time DESC')->group('group_id')->limit($page->firstRow .',' . $page->listRows)->select();

			foreach ($list as $key => $value) {
				$list[$key]['is_admin'] = 0;
				// $tmp = explode(',', $value['live_user_num']);
				// $list[$key]['live_full_name'] = '';
				// if(count($tmp) == 1) {
					$list[$key]['live_full_name'] = M('UserInfo')->where(array('uid' => $value['user_id']))->getField('realname'); 
				// }

				// $tmp = M('UserInfo')->field('realname')->where(array('uid' => array('in', $value['user_id'])))->find();
				// $list[$key]['uname'] = $tmp['realname'];
			}

		} else {
			// $where['user_id'] = $this->uid;
			// $where['column_id'] = array('in', $chids);
			// $where['_logic'] = 'or';
			// $map['_complex'] = $where;
			// $map['v_status'] = array('NEQ', -1);

			// $model = M('Live');
			// $total = $model->where($map)->group('group_id')->count();
			// $page = new \Think\Page($total, $pageSize);
			// $list = $model->field('id, start_time,v_status,z_status,user_id,apply_id,address,title,group_id,group_status,column_id,group_num as live_user_num,is_direction')->where($map)->order('start_time DESC')->group('group_id')->limit($page->firstRow .',' . $page->listRows)->select();
			
			$model = M('Live');
			// 取出自己的
			$ownerList = $model->where(array('user_id' => $this->uid,'v_status'=>array('GT',-1)))->select();
			$ownerGroup = $ownerIds = array();
			foreach ($ownerList as $key => $value) {
				$ownerGroup[] = $value['group_id'];
				$ownerIds[] = $value['id'];
			}

			// 取出自己可以管理的其他人的直播
			$otherIds = array();
			$otherList = $model->where(array('column_id' => array('in', $chids),'v_status'=>array('GT',-1)))->group('group_id')->select();
			foreach($otherList as $key => $value) {
				if(!in_array($value['group_id'], $ownerGroup)) {
					$otherIds[] = $value['id'];
				}
			}

			$searchIds = array_merge($ownerIds, $otherIds);

			$model = M('Live');
			$total = $model->where(array('id' => array('in', $searchIds)))->count();
			$page = new \Think\Page($total, $pageSize);
			$list = $model->field('id, start_time,v_status,z_status,user_id,apply_id,address,title,group_id,group_status,column_id,group_num as live_user_num,is_direction')->where(array('id' => array('in', $searchIds)))->order('start_time DESC')->limit($page->firstRow .',' . $page->listRows)->select();

			// echo $model->getLastsql();exit;
			foreach ($list as $key => $value) {
				// $tmp = explode(',', $value['live_user_num']);
				// $list[$key]['live_full_name'] = '';
				// if(count($tmp) == 1) {
					$list[$key]['live_full_name'] = M('UserInfo')->where(array('uid' => $value['user_id']))->getField('realname');
				// }

				if(in_array($value['column_id'], $chids)) {
					$list[$key]['is_admin'] = 1;
					$list[$key]['z_status'] = $value['group_status'];
					unset($list[$key]['group_status']);
				} else {
					$list[$key]['is_admin'] = 0;
				}
				// $tmp = M('UserInfo')->field('realname')->where(array('uid' => array('in', $value['user_id'])))->find();
				// $list[$key]['uname'] = $tmp['realname'];
				// $list[$key]['start_time'] = date('Y-m-d H:i:s', $value['start_time']);
				// $list[$key]['end_time'] = date('Y-m-d H:i:s', $value['end_time']);
				// $list[$key]['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
			}
		}

		// echo $model->getLastsql();exit;

		if($list) {
			$message['resultCode'] = 0;
			$message['message'] = '';
			$message['list'] = $list;
			$this->ajaxReturn($message);
		} else {
			$message['resultCode'] = 0;
			$message['message'] = '未找到记录';
			$message['list'] = array();
			$this->ajaxReturn($message);
		}
	}

	/**
	 * 通过直播
	 * @return [type] [description]
	 */
	public function passLive() {
		apigetpost();

		if(IS_POST) {
			$id = I('post.id'); // 组ID

			if($id) {

				$map['id'] = $id;
				$liveinfo = M('Live')
		                   ->alias('l')
		                   ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
		                   ->field("l.*,ch.relation")
		                   ->where($map)->find();

		        if($liveinfo) {
		        	$approve = unserialize($liveinfo['relation']);
		        	$uidList = array();
		        	if(in_array($this->uid,$approve[0])){
		        		$res = M('Live')->where(array('group_id' => $liveinfo['group_id']))->save(array('v_status' => 1, 'v_user_id' => $this->uid, 'apply_time' => time()));

		        		if($res !== false) {

			        		// $mkHTML=new \Common\Util\makeHTML();
	       					// $mkHTML-> ByGroupId($liveinfo['group_id']);

		   					foreach($approve[0] as $key => $val) {
		   						if($this->uid != $val)
		   							$uidList[] = $val;
		   					}  		        			

			   				if($this->uid != $liveinfo['apply_id']) {
			   					$uidList[] = $liveinfo['apply_id'];
			   					$uidList = array_unique($uidList);
			   				}

			   				// \Think\Log::write(implode(',', $uidList),'uidList');

			   				$trans=json_encode(array('pushCode'=>300,'objectId'=>$id,'userId'=>0));
							sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'《' . $liveinfo['title'] . '》直播通过审核','trans'=>$trans));			   				

							$message['resultCode'] = 0;
							$message['message'] = '审核已通过';
		        		} else {
							$message['resultCode'] = 1;
							$message['message'] = '服务器端异常';
		        		}
		        	} else {
						$message['resultCode'] = 1;
						$message['message'] = '没有权限修改';
		        	}

		        } else {
					$message['resultCode'] = 1;
					$message['message'] = 'ID未知';
		        }


			} else {
				$message['resultCode'] = 1;
				$message['message'] = '未知ID';
			}
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '非法操作';
		}

		$this->ajaxReturn($message);
	}

	/**
	 * 拒绝直播
	 * @return [type] [description]
	 */
	public function uncallLive() {
		apigetpost();

		if(IS_POST) {
			$id = I('post.id');
			$reason = I('post.reason');

			if($id) {

				$map['id'] = $id;
				$liveinfo = M('Live')
		                   ->alias('l')
		                   ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
		                   ->field("l.*,ch.relation")
		                   ->where($map)->find();
		        if($liveinfo) {
		        	$approve = unserialize($liveinfo['relation']);
		        	if(in_array($this->uid,$approve[0])){
		        		$res = M('Live')->where(array('group_id' => $liveinfo['group_id']))->save(array('v_status' => 3 , 'v_user_id' => $this->uid, 'back_reason' => $reason,'apply_time' => time()));
		        		if($res !== false) {

		   					foreach($approve[0] as $key => $val) {
		   						if($this->uid != $val)
		   							$uidList[] = $val;
		   					}  		        			

			   				if($this->uid != $liveinfo['apply_id']) {
			   					$uidList[] = $liveinfo['apply_id'];
			   					$uidList = array_unique($uidList);
			   				}
			   				// \Think\Log::write(implode(',', $uidList),'uidList');

			   				$trans=json_encode(array('pushCode'=>300,'objectId'=>$id,'userId'=>0));
							sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'《' . $liveinfo['title'] . '》直播审核未通过，已退稿','trans'=>$trans));			   				

							$message['resultCode'] = 0;
							$message['message'] = '直播已被拒绝';
		        		} else {
							$message['resultCode'] = 1;
							$message['message'] = '服务器端异常';
		        		}
		        	} else {
						$message['resultCode'] = 1;
						$message['message'] = '没有权限修改';
		        	}

		        } else {
					$message['resultCode'] = 1;
					$message['message'] = 'ID未知';
		        }

			} else {
				$message['resultCode'] = 1;
				$message['message'] = '未知ID';
			}
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '非法操作';
		}

		$this->ajaxReturn($message);
	}

	/**
	 * 直播详情
	 * @return [type] [description]
	 */
	public function liveInfo() {
		apigetpost();

		$id = I('get.id');

		if($id) {
			$map['id'] = $id;
			$liveinfo = M('Live')
	                   ->alias('l')
	                   ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
	                   ->field("l.id,l.user_id,l.title,l.v_status,l.z_status,l.group_id,l.apply_id,l.intro,ch.relation,l.back_reason,l.v_user_id,l.start_time,l.address,l.group_status,l.apply_time")
	                   ->where($map)->find();

	        if($liveinfo) {
	        	$approve = unserialize($liveinfo['relation']);
	        	if($liveinfo['user_id'] == $this->uid || in_array($this->uid,$approve[0])){
	        		if(in_array($this->uid,$approve[0])) {
	        			$liveinfo['is_admin'] = 1;
	        			if($liveinfo['v_status'] == 0) {
	        				M('Live')->where(array('group_id' => $liveinfo['group_id']))->save(array('v_status' => 2));
	        				$liveinfo['v_status'] = 2;
	        			}
	        			
	        		} else {
	        			$liveinfo['is_admin'] = 0;
	        		}

					$liveinfo['apply_name'] = M('UserInfo')->where(array('uid' => $liveinfo['apply_id']))->getField('realname');	 // 申请人的姓名

					$liveinfo['verify_name'] = M('UserInfo')->where(array('uid' => $liveinfo['v_user_id']))->getField('realname');

					$other_list = M('Live')->field('id,user_id,title')->where(array('group_id' => $liveinfo['group_id']))->order('id DESC')->select();
					foreach ($other_list as $key => $value) {
						$name = M('UserInfo')->where(array('uid' => $value['user_id']))->getField('realname');
						$liveinfo['full_names'] .= ',' . $name; // 直播人姓名，逗号分割
						$liveinfo['live_ids'] .=  ',' . $value['user_id'];
						// $liveinfo['other_list'][$key] = $value;
						// $liveinfo['other_list'][$key]['uname'] = M('UserInfo')->where(array('uid' => $value['user_id']))->getField('realname');
						// $liveinfo['other_list'][$key]['vname'] = M('UserInfo')->where(array('uid' => $value['apply_id']))->getField('realname');
					}

					$liveinfo['live_ids'] = trim($liveinfo['live_ids'], ',');
					$liveinfo['full_names'] = trim($liveinfo['full_names'], ',');

					unset($liveinfo['relation']);

					$liveinfo['id']=$id;

					$message['resultCode'] = 0;
					$message['message'] = '';
					$message['liveinfo'] = $liveinfo;

	        	} else {
					$message['resultCode'] = 1;
					$message['message'] = '没有权限查看';
	        	}

	        } else {
				$message['resultCode'] = 1;
				$message['message'] = 'ID未知';
	        }

		} else {
			$message['resultCode'] = 1;
			$message['message'] = '未知ID';
		}

		$this->ajaxReturn($message);
	}


	/**
	 * 获取推流地址
	 * @return [type] [description]
	 */
	public function getPushStreamUrl() {
		$id = I('get.id');
		if($id) {
			$model = M('Live');
			$info = $model
			->alias('l')
			->where(array('l.id' => $id))
			->join('__USER_INFO__ ui ON l.user_id=ui.uid')
			->find();
			if($info) {
				$message['resultCode'] = 0;
				$message['message'] = '';
				if($info['userchannel']==55 || $info['is_device']==1){

					$message['url'] = authAliyun('rtmp://video-center.alivecdn.com/jw/' . $info['realnamepy'] . '?vhost=jwlive.appwuhan.com',time()+3600*24*365*20);
				} elseif($info['userchannel']==57) {
					$message['url'] = authAliyun('rtmp://video-center.alivecdn.com/jwdev/' . $info['group_id'] . '_' . $info['user_id'] . '?vhost=jwlive.appwuhan.com');
				}else{
					$message['url'] = authAliyun('rtmp://video-center.alivecdn.com/jw/' . $info['group_id'] . '_' . $info['user_id'] . '?vhost=jwlive.appwuhan.com');
					//$message['url'] = authAliyun('rtmp://jwtest.appwuhan.com/jw/' . $info['group_id'] . '_' . $info['user_id']); 
				}

			} else {
				$message['resultCode'] = 1;
				$message['message'] = '直播不存在';
			}

		} else {
			$message['resultCode'] = 1;
			$message['message'] = '未知ID';
		}

		$this->ajaxReturn($message);
	}

	/**
	 * 获取播流地址
	 * @return [type] [description]
	 */
	public function getStreamUrl() {
		$id = I('get.id');
		if($id) {
			$model = M('Live');
			$info = $model->alias('l')
            ->where(array('id' => $id))
            ->join('__USER_INFO__ ui ON l.user_id=ui.uid')
            ->find();
			if($info) {
				$message['resultCode'] = 0;
				$message['message'] = '';

				if($info['z_status'] == 3) {
					 $message['url'] = $info['return_live'] ? $info['return_live'] : '';
					 $message['type'] = 1; // 是否回看
				} elseif($info['z_status'] == 0) {
					$message['url'] = '';
					$message['type'] = 0;
				} else {

	                if($info['group_id']=='20171208142808_595_5a2a30f89ad97'){
                        $url=$info['return_live'];
                    }if($info['userchannel']==55 || $info['is_device']==1){
	                    $message['url'] = authAliyun('rtmp://jwlive.appwuhan.com/jw/' . $info['realnamepy']);
	                } elseif($info['userchannel']==57) {
						$message['url'] = authAliyun('rtmp://jwlive.appwuhan.com/jwdev/' . $info['group_id'] . '_' . $info['user_id']);    
	                }elseif($info['group_id'] == '20171228165845_726_5a44b24541a62') {//交通频率24小时直播
                        $message['url'] ='rtmp://pili-live-hls.qnlive.appwuhan.com/jianwei/896';
                	}else{
	                    $message['url'] = authAliyun('rtmp://jwlive.appwuhan.com/jw/' . $info['group_id'] . '_' . $info['user_id']);
	                }
	                $message['type'] = 0;
	            }    
			} else {
				$message['resultCode'] = 1;
				$message['message'] = '直播不存在';
			}

		} else {
			$message['resultCode'] = 1;
			$message['message'] = '未知ID';
		}

		$this->ajaxReturn($message);
	}

	/**
	 * 修改直播信息
	 * @return [type] [description]
	 */
	public function editLive() {
		apigetpost();
		if(IS_POST) {
			$model = D('Live');

			$live_id = I('post.id');
			if(empty($live_id)) {
				$message['resultCode'] = 1;
				$message['message'] = '未知ID';	
				$this->ajaxReturn($message);	
			}

			$info = $model->where(array('id' => $live_id))->find();

			if(empty($info)) {
				$message['resultCode'] = 1;
				$message['message'] = '资源不存在';	
				$this->ajaxReturn($message);	
			}

			if($info['apply_id'] == $this->uid) {

				$group_id = $info['group_id'];
				$old_source_list = $model->where(array('group_id' => $group_id))->select();
				if(empty($old_source_list)) {
					$message['resultCode'] = 1;
					$message['message'] = '资源不存在';	
					$this->ajaxReturn($message);	
				}

				$old_list = array();
				foreach($old_source_list as $val) {
					$old_list[] = $val['user_id'];
				}
		
				$dataGet['title'] = I('post.title');
				$user_ids = I('post.user_ids', ''); // 直播人ID
				$dataGet['start_time'] = strtotime(I('post.start_time'));
				$dataGet['address'] = I('post.address');
				$dataGet['intro'] = I('post.intro');

				$user_ids = $user_ids ? explode(',', $user_ids) : array();

				if(in_array($this->uid, $user_ids)) {
					$key = array_search($this->uid, $user_ids); 
					unset($user_ids[$key]);
				}

				$user_ids[] = $this->uid;
				$user_ids = array_unique($user_ids);

				$channelres=M('UserInfo')->alias('ui')
				->join('__CHANNEL__ c on ui.userchannel=c.chid')
				->where(array('ui.uid' => $this->uid))->find();
				$dataGet['column_id'] = $channelres['userchannel'];

				if($model->create($dataGet)) {
					try {
						M()->startTrans();
						if($user_ids) {
							$diff = array_diff($user_ids, $old_list);
							if(!empty($diff) || (empty($diff) && count($user_ids) != count($old_list))) {
								$d_status = M('Live')->where(array('group_id' => $group_id))->delete();
								if ($d_status) {
									foreach ($user_ids as $id) {
										$dataGet['user_id'] = $id;
										$dataGet['apply_id'] = $this->uid;
										$dataGet['group_id'] = $group_id;
										$dataGet['group_num'] = implode(',', array_reverse($user_ids));
										$dataGet['create_time'] = time();
										$dataGet['update_time'] = time();
										$dataGet['rand'] = $info['rand'];//2018.01.29添加 修复：修改直播详情，添加直播人的时候，出现rand变0

										$tmp[$k]['id'] = $id;
										$tmp[$k]['stream'] = $group_id . '_' . $id;

										liveStatus(2, $tmp, -1);

										$res = $model->add($dataGet);
										if (!$res)
											throw new \Exception('服务器异常');
									}
								} else {
									throw new \Exception('服务器异常');
								}
							} else {
								foreach($user_ids as $id) {
									// $dataGet['user_id'] = $id;
									$dataGet['apply_id'] = $this->uid;
									$dataGet['group_id'] = $group_id;
									$dataGet['v_status'] = 0;
									$dataGet['group_num'] = implode(',', array_reverse($user_ids));
									$dataGet['update_time'] = time();

									$res = $model->where(array('group_id' => $group_id, 'user_id' => $id))->save($dataGet);
									if($res == false)
										throw new \Exception('服务器异常');
								}
							}

						} else {
							throw new \Exception('申请失败，请重试');
						}

						M()->commit();

						$relation = unserialize($channelres['relation']);
						$uidList = array();
						if(in_array($this->uid, $relation[0])) {
							foreach ($relation[0] as $key => $value) {
								if($value != $this->uid)
									$uidList[] = $value;
							}
						} else {
							$uidList = $relation[0];
						}
						$trans=json_encode(array('pushCode'=>300,'objectId'=>$live_id,'userId'=>0));
						sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>$channelres['realname'] . '修改直播《' . $dataGet['title'] . '》，请审核！','trans'=>$trans));

						$message['resultCode'] = 0;
						$message['message'] = '修改成功';

					} catch (\Exception $e) {
						M()->rollback();
						$message['resultCode'] = 1;
						$message['message'] = $e->getMessage();
					}

				} else {
					$message['resultCode'] = 1;
					$message['message'] = $model->getError();
				}
			} else {
				$message['resultCode'] = 1;
				$message['message'] = '无修改权限';			
			}	
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '非法请求';
		}

		$this->ajaxReturn($message);
	}

	/**
	 * 检查审核状态
	 * @return [type] [description]
	 */
	public function checkLive() {
		apigetpost();
		$id = I('get.id');

		if($id) {
			$map['id'] = $id;
			$liveinfo = M('Live')
	                   ->alias('l')
	                   ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
	                   ->field("l.id,l.user_id,l.title,l.v_status,l.z_status,l.group_id,l.apply_id,l.intro,ch.relation,l.back_reason,l.v_user_id,l.start_time,l.address,l.group_status")
	                   ->where($map)->find();

	        if($liveinfo) {
	        	$approve = unserialize($liveinfo['relation']);
	        	if($liveinfo['user_id'] == $this->uid || in_array($this->uid,$approve[0])){
	        		$status['v_status'] =  $liveinfo['v_status'];
	        		if(in_array($this->uid,$approve[0])) {
	        			$status['z_status'] = $liveinfo['group_status'];
	        		} else {
	        			$status['z_status'] = $liveinfo['z_status'];
	        		}

					$message['resultCode'] = 0;
					$message['message'] = '';
					$message['z_status'] = $status['z_status'];
					$message['v_status'] = $status['v_status'];
					// $message['status'] = $status;

	        	} else {
					$message['resultCode'] = 1;
					$message['message'] = '没有权限查看';
	        	}

	        } else {
				$message['resultCode'] = 1;
				$message['message'] = 'ID未知';
	        }

		} else {
			$message['resultCode'] = 1;
			$message['message'] = '未知ID';
		}

		$this->ajaxReturn($message);
	}

	/**
	 * 撤销直播
	 * @return [type] [description]
	 */
	public function revocationLive() {
		apigetpost();
		$id = I('post.id');

		if($id) {
			$map['id'] = $id;
			$liveinfo = M('Live')
	                   ->alias('l')
	                   ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
	                   ->field("l.id,l.user_id,l.title,l.v_status,l.z_status,l.group_id,l.apply_id,l.intro,ch.relation,l.back_reason,l.v_user_id,l.start_time,l.address,l.group_status")
	                   ->where($map)->find();

	        if($liveinfo) {
	        	$approve = unserialize($liveinfo['relation']);
	        	if($liveinfo['apply_id'] == $this->uid){
	        		$res = M('Live')->where(array('group_id' => $liveinfo['group_id']))->save(array(
	        			'v_status' => -1,
	        		));

	        		if($res !== false) {
	        			if($liveinfo['v_status'] == 0) {
		        			if(in_array($this->uid, $approve[0])) {        			
			   					foreach($approve[0] as $key => $val) {
			   						if($this->uid != $val)
			   							$uidList[] = $val;
			   					}  
							} else {
								$uidList = $approve[0];
							}
			   				$trans=json_encode(array('pushCode'=>300,'objectId'=>$id,'userId'=>0));
							sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'《' . $liveinfo['title'] . '》直播已被撤销','trans'=>$trans));
						}

						$message['resultCode'] = 0;
						$message['message'] = '修改成功';       			
	        		} else {
   						$message['resultCode'] = 1;
						$message['message'] = '服务器异常';    			
	        		}

	        	} else {
					$message['resultCode'] = 1;
					$message['message'] = '没有权限修改';
	        	}

	        } else {
				$message['resultCode'] = 1;
				$message['message'] = 'ID未知';
	        }

		} else {
			$message['resultCode'] = 1;
			$message['message'] = '未知ID';
		}

		$this->ajaxReturn($message);
	}

	/**
	 * 删除
	 * @return [type] [description]
	 */
	public function deleteLive() {
		apigetpost();
		$id = I('post.id');	
		if($id) {
			$map['id'] = $id;
			$liveinfo = M('Live')
	                   ->alias('l')
	                   ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
	                   ->field("l.*,ch.relation")
	                   ->where($map)->find();
		
			// $liveinfo = M('Live')->where(array('id' => $id))->find();
			if($liveinfo) {
				$approve = unserialize($liveinfo['relation']);
	        	if($liveinfo['apply_id'] == $this->uid){
	        		$res = M('Live')->where(array('group_id' => $liveinfo['group_id']))->delete();

	        		if($res) {
		
	        			if(in_array($this->uid, $approve[0])) {        			
		   					foreach($approve[0] as $key => $val) {
		   						if($this->uid != $val)
		   							$uidList[] = $val;
		   					}  
						} else {
							$uidList = $approve[0];
						}

						// \Think\Log::write(implode(',', $uidList),'uidList');
		   				$trans=json_encode(array('pushCode'=>300,'objectId'=>$id,'userId'=>0));
						sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'《' . $liveinfo['title'] . '》直播已被删除','trans'=>$trans));						

						$message['resultCode'] = 0;
						$message['message'] = '删除成功';       			
	        		} else {
   						$message['resultCode'] = 1;
						$message['message'] = '服务器异常';    			
	        		}

	        	} else {
					$message['resultCode'] = 1;
					$message['message'] = '没有权限删除';
	        	}

	        } else {
				$message['resultCode'] = 1;
				$message['message'] = 'ID未知';
	        }

		} else {
			$message['resultCode'] = 1;
			$message['message'] = '未知ID';
		}

		$this->ajaxReturn($message);
	} 

	public function getPhone() {
		$info = M('SystemConfig')->where('config = "phone"')->getField('value');
		if($info) {
			$message['resultCode'] = 0;
			$message['message'] = '';
			$message['phone'] = $info;
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '未找到手机号';		
		}


		$this->ajaxReturn($message);
	}

	/**
	 * 获取我的直播列表
	 * @return [type] [description]
	 */
	public function getOwnerLiveList() {
		apigetpost();

		$pageSize = I('get.pageSize', 10);
		C('VAR_PAGE', 'page');

		$channel = M('Channel')->field('chid, relation')->select();
		$chids = array();
		foreach($channel as $val) {
			$val['relation'] && $val['relation'] = unserialize($val['relation']);
			if(isset($val['relation'][0]) && !empty($val['relation'][0])) {
				if(in_array($this->uid, $val['relation'][0])) {
					$chids[] = $val['chid'];
				}
			}
		}

		if(empty($chids)) {
			$map['user_id'] = $this->uid;
			// $map['z_status'] = array('GT', 0);
			$model = M('Live');
			$total = $model->where($map)->group('group_id')->count();
			$page = new \Think\Page($total, $pageSize);
			$list = $model->field('id, start_time,v_status,z_status,user_id,apply_id,address,title,group_id,group_num as live_user_num,is_direction')->where($map)->order('update_time DESC')->group('group_id')->limit($page->firstRow .',' . $page->listRows)->select();

			foreach ($list as $key => $value) {
				$list[$key]['is_admin'] = 0;
				$list[$key]['live_full_name'] = M('UserInfo')->where(array('uid' => $value['user_id']))->getField('realname'); 

			}	
		} else {
			// $where['user_id'] = $this->uid;
			// $where['column_id'] = array('in', $chids);
			// $where['_logic'] = 'or';
			// $map['_complex'] = $where;
			// $map['z_status'] = array('GT', 0);

			// $model = M('Live');
			// $total = $model->where($map)->group('group_id')->count();
			// $page = new \Think\Page($total, $pageSize);
			// $list = $model->field('id, start_time,v_status,z_status,user_id,apply_id,address,title,group_id,group_status,column_id,group_num as live_user_num,is_direction')->where($map)->order('update_time DESC')->group('group_id')->limit($page->firstRow .',' . $page->listRows)->select();

			$model = M('Live');
			// 取出自己的
			$ownerList = $model->where(array('user_id' => $this->uid,'v_status'=>array('in',array(0,1,2,3))))->select();
			$ownerGroup = $ownerIds = array();
			foreach ($ownerList as $key => $value) {
				$ownerGroup[] = $value['group_id'];
				$ownerIds[] = $value['id'];
			}

			// 取出自己可以管理的其他人的直播
			$otherIds = array();
			$otherList = $model->where(array('column_id' => array('in', $chids),'v_status'=>array('in',array(0,1,2,3))))->group('group_id')->select();
			foreach($otherList as $key => $value) {
				if(!in_array($value['group_id'], $ownerGroup)) {
					$otherIds[] = $value['id'];
				}
			}

			// $searchIds = array_merge($ownerIds, $otherIds);
		$searchIds = $ownerIds;
			$model = M('Live');
			$total = $model->where(array('id' => array('in', $searchIds)))->count();
			$page = new \Think\Page($total, $pageSize);
			$list = $model->field('id, start_time,v_status,z_status,user_id,apply_id,address,title,group_id,group_status,column_id,group_num as live_user_num,is_direction')->where(array('id' => array('in', $searchIds)))->order('start_time DESC')->limit($page->firstRow .',' . $page->listRows)->select();

			foreach ($list as $key => $value) {
				$list[$key]['live_full_name'] = M('UserInfo')->where(array('uid' => $value['user_id']))->getField('realname');

				if(in_array($value['column_id'], $chids)) {
					$list[$key]['is_admin'] = 1;
						$list[$key]['z_status'] = $value['group_status'];
					unset($list[$key]['group_status']);
				} else {
					$list[$key]['is_admin'] = 0;
				}
			}
		}

		if($list) {
			$message['resultCode'] = 0;
			$message['message'] = '';
			$message['list'] = $list;
			$this->ajaxReturn($message);
		} else {
			$message['resultCode'] = 0;
			$message['message'] = '未找到记录';
			$message['list'] = array();
			$this->ajaxReturn($message);
		}
	}

	/**
	 * 直播申请
	 * @return [type] [description]
	 */
	public function getOwnerApplyList() {
		apigetpost();

		$pageSize = I('get.pageSize', 10);
		C('VAR_PAGE', 'page');

		$channel = M('Channel')->field('chid, relation')->select();
		$chids = array();
		foreach($channel as $val) {
			$val['relation'] && $val['relation'] = unserialize($val['relation']);
			if(isset($val['relation'][0]) && !empty($val['relation'][0])) {
				if(in_array($this->uid, $val['relation'][0])) {
					$chids[] = $val['chid'];
				}
			}
		}

		if(empty($chids)) {
			$map['user_id'] = $this->uid;
			$map['z_status'] = 0;
			$map['v_status'] = array('NEQ', -1);
			$model = M('Live');
			$total = $model->where($map)->group('group_id')->count();
			$page = new \Think\Page($total, $pageSize);
			$list = $model->field('id, start_time,v_status,z_status,user_id,apply_id,address,title,group_id,group_num as live_user_num,is_direction')->where($map)->order('update_time DESC')->group('group_id')->limit($page->firstRow .',' . $page->listRows)->select();

			foreach ($list as $key => $value) {
				$list[$key]['is_admin'] = 0;
				$list[$key]['live_full_name'] = M('UserInfo')->where(array('uid' => $value['user_id']))->getField('realname'); 

			}

		} else {
			$where['user_id'] = $this->uid;
			$where['column_id'] = array('in', $chids);
			$where['_logic'] = 'or';
			$map['_complex'] = $where;
			// $map['z_status'] = 0;
			// $map['v_status'] = array('NEQ', -1);
	
			$map['v_status'] = array('in', array(0,1,2,3));

			$model = M('Live');
			$total = $model->where($map)->group('group_id')->count();
			$page = new \Think\Page($total, $pageSize);
			$list = $model->field('id, start_time,v_status,z_status,user_id,apply_id,address,title,group_id,group_status,column_id,group_num as live_user_num,is_direction')->where($map)->order('update_time DESC')->group('group_id')->limit($page->firstRow .',' . $page->listRows)->select();
			// echo $model->getLastsql();exit;
			foreach ($list as $key => $value) {
				$list[$key]['live_full_name'] = M('UserInfo')->where(array('uid' => $value['user_id']))->getField('realname'); 

				if(in_array($value['column_id'], $chids)) {
					$list[$key]['is_admin'] = 1;
					$list[$key]['z_status'] = $value['group_status'];
					unset($list[$key]['group_status']);
				} else {
					$list[$key]['is_admin'] = 0;
				}
			}
		}


		if($list) {
			$message['resultCode'] = 0;
			$message['message'] = '';
			$message['list'] = $list;
			$this->ajaxReturn($message);
		} else {
			$message['resultCode'] = 0;
			$message['message'] = '未找到记录';
			$message['list'] = array();
			$this->ajaxReturn($message);
		}
	}


	/**
	 * 开始直播
	 */
	public function startLive() {
		apigetpost();
		$id = I('post.id');
		$direction = I('post.direction'); 
		if($id) {
			$group_id = M('Live')->where(array('id' => $id))->getField('group_id');

			if($group_id) {
				$map1['group_id'] = $group_id;
				$count1 = M('Live')->where($map1)->count();	

				// 只允许z_status为1的情况下修改状态为2
				$res = M('Live')->where(array('id' => $id, 'z_status' => 1))->save(array(
					'z_status' => 2,
					'is_direction' => $direction, // 屏幕方向
				));

				if($res !== false) {
					$map2['group_id'] = $group_id;
					$map2['z_status'] = array('EQ', 2);
					$count2 = M('Live')->where($map2)->count();	
					
					if($count1 == $count2) {
						M('Live')->where(array('group_id' => $group_id))->save(array(
							'group_status' => 2,
						));
					}

					$message['resultCode'] = 0;
					$message['message'] = '';

				} else {
					$message['resultCode'] = 1;
					$message['message'] = '服务器异常';						
				}

			} else {
				$message['resultCode'] = 1;
				$message['message'] = '此直播不存在';			
			}

		} else {
			$message['resultCode'] = 1;
			$message['message'] = '未知ID';			
		}

		$this->ajaxReturn($message);

	}


	/**
	 * 暂停直播，申请人调用
	 */
	public function pauseLive() {
		apigetpost();
		$id = I('post.id');
		if($id) {
			$group_id = M('Live')->where(array('id' => $id))->getField('group_id');

			if($group_id) {
				$map1['group_id'] = $group_id;
				$count1 = M('Live')->where($map1)->count();

				$res = M('Live')->where(array('id' => $id,'z_status' => 2))->save(array(
					'z_status' => 1,
					'update_time' => time(),
				));

				if($res !== false) {
					$map2['group_id'] = $group_id;
					$map2['z_status'] = array('EQ', 1);
					$count2 = M('Live')->where($map2)->count();

					if($count1 == $count2) {
						M('Live')->where(array('group_id' => $group_id))->save(array(
							'group_status' => 1,
						));
					}

					$message['resultCode'] = 0;
					$message['message'] = '';

				} else {
					$message['resultCode'] = 1;
					$message['message'] = '服务器异常';
				}

			} else {
				$message['resultCode'] = 1;
				$message['message'] = '此直播不存在';
			}

		} else {
			$message['resultCode'] = 1;
			$message['message'] = '未知ID';
		}

		$this->ajaxReturn($message);
	}

	/**
	 * 中断直播
	 * @return [type] [description]
	 */
	public function offLive() {

		apigetpost();
		$id = I('post.id');
		if($id) {
			$group_id = M('Live')->where(array('id' => $id))->getField('group_id');

			if($group_id) {
				$map1['group_id'] = $group_id;
				$count1 = M('Live')->where($map1)->count();

				$res = M('Live')->where(array('id' => $id/*,'z_status' => array('in',array(1,2))*/))->save(array(
					'z_status' => 0,
				));

				if($res !== false) {
					$map2['group_id'] = $group_id;
					$map2['z_status'] = array('EQ', 0);
					$count2 = M('Live')->where($map2)->count();

					if($count1 == $count2) {
						M('Live')->where(array('group_id' => $group_id))->save(array(
							'group_status' => 0,
						));
					}

					$user_id = M('Live')->where(array('id' => $id))->getField('user_id');
					liveStatus(2, array(array('id'=>$id,'stream'=>$group_id . '_' .$user_id)), -1); // 掐流

					$info = M('Live')->where(array('id' => $id))->find();

					$trans=json_encode(array('pushCode'=>302,'objectId'=>$id,'userId'=>0));
					sock_post('http://localhost/Mapi/Tui/pushUid.html', array('uid'=>$info['user_id'],'title'=>'见微','content'=>'《' . $info['title'] .' 》直播通道已关闭','trans'=>$trans));

					$message['resultCode'] = 0;
					$message['message'] = '';

				} else {
					$message['resultCode'] = 1;
					$message['message'] = '服务器异常';
				}

			} else {
				$message['resultCode'] = 1;
				$message['message'] = '此直播不存在';
			}

		} else {
			$message['resultCode'] = 1;
			$message['message'] = '未知ID';
		}

		$this->ajaxReturn($message);
	}

	/**
	 * 结束直播
	 * @return [type] [description]
	 */
	public function overLive() {

		apigetpost();
		$id = I('post.id');
		if($id) {
			$group_id = M('Live')->where(array('id' => $id))->getField('group_id');

			if($group_id) {
				$map1['group_id'] = $group_id;
				$count1 = M('Live')->where($map1)->count();

				$res = M('Live')->where(array('id' => $id))->save(array(
					'z_status' => 3,
				));

				if($res !== false) {
					$map2['group_id'] = $group_id;
					$map2['z_status'] = array('EQ', 3);
					$count2 = M('Live')->where($map2)->count();

					if($count1 == $count2) {
						M('Live')->where(array('group_id' => $group_id))->save(array(
							'group_status' => 3,
						));
					}

					$user_id = M('Live')->where(array('id' => $id))->getField('user_id');
					liveStatus(2, array(array('id'=>$id,'stream'=>$group_id . '_' .$user_id)), -1); // 掐流

					$map['id'] = $id;
					$liveinfo = M('Live')
		                   ->alias('l')
		                   ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
		                   ->field("l.*,ch.relation")
		                   ->where($map)->find();

		            $approve = unserialize($liveinfo['relation']); 

		            if(in_array($this->uid, $approve[0])) {
			            $uidList = array(); 
	   					foreach($approve[0] as $key => $val) {
	   						if($this->uid != $val)
	   							$uidList[] = $val;
	   					} 

						if($this->uid != $liveinfo['apply_id']) {
		   					$uidList[] = $liveinfo['apply_id'];
		   				}
		   				$uidList = array_unique($uidList);

						$trans=json_encode(array('pushCode'=>300,'objectId'=>$id,'userId'=>0));
						sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'《' . $liveinfo['title'] .' 》直播已结束','trans'=>$trans));		            	
		            }  


					$message['resultCode'] = 0;
					$message['message'] = '';

				} else {
					$message['resultCode'] = 1;
					$message['message'] = '服务器异常';
				}

			} else {
				$message['resultCode'] = 1;
				$message['message'] = '此直播不存在';
			}

		} else {
			$message['resultCode'] = 1;
			$message['message'] = '未知ID';
		}

		$this->ajaxReturn($message);

	}


	/**
	 * 直播通道开启，管理员调用
	 */
	public function startLivePipeByAdmin() {
		apigetpost();
		$live_id = I('post.id');
		 if($live_id){
            $info = M('Live')->where(array('id' => $live_id))->find();

            $res = liveStatus(2, array(array('id'=>$live_id,'stream'=>$info['group_id'] . '_' . $info['user_id'])),1);
            if($res['status'] == 0) {
                M('Live')->where(array('id' => $live_id))->save(array(
                    'update_time' => time(),
                )); 

                if($info['group_status'] != 1) {
                    $r = M('Live')->where(array('group_id' => $info['group_id']))->save(array(
                        'group_status' => 1,
                    ));  
                    $message['groupId'] = 1;             
                }

                // 推送
                $map['id'] = $live_id;
                $liveinfo = M('Live')
                    ->alias('l')
                    ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
                    ->field("l.id,l.user_id,l.title,l.v_status,l.z_status,l.group_id,l.apply_id,l.intro,ch.relation,l.back_reason,l.v_user_id,l.start_time,l.address,l.group_status")
                    ->where($map)->find();
                $uidList = array();
                $approve = unserialize($liveinfo['relation']);
                $uidList = $approve[0];

                foreach ($uidList as $key => $value) {
                    if($value == $liveinfo['user_id'])
                        unset($uidList[$key]);
                }

                // $uidList[] = $liveinfo['user_id'];
                $uidList = array_unique($uidList);
                $livename = M('UserInfo')->where(array('uid' => $liveinfo['user_id']))->getField('realname');
                
                // 推送直播人
                $trans=json_encode(array('pushCode'=>301,'objectId'=>$live_id,'userId'=>0,'liveTitle' => $liveinfo['title']));
                sock_post('http://localhost/Mapi/Tui/pushUid.html', array('uid'=>$liveinfo['user_id'],'title'=>'见微','content'=>'直播人：' . $livename . '的《' . $liveinfo['title'] . '》直播通道已开启','trans'=>$trans));  


                if($message['groupId'] == 1) {
                    $trans=json_encode(array('pushCode'=>300,'objectId'=>$live_id,'userId'=>0));
                    sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'《' . $liveinfo['title'] . '》直播通道已开启','trans'=>$trans));
                }  

                $message['resultCode'] = 0;
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);               

            } else {
                $message['resultCode'] = 1;
                $message['msg'] = '服务器异常';
                $this->ajaxReturn($message);
            }
        }

	}


public function updateLivePushInfo() {
		apigetpost();
		$live_id = I('post.id', 0);
		$record_id = I('post.rid', 0); // 记录ID
		$live_push_size = I('post.live_push_size');
		$live_network_type = I('post.live_network_type');
		
		if($live_id) {
			$add = M('Live')->where(array('id' => $live_id))->setInc('live_push_size', $live_push_size); // 增加

			if($add !== false) {
				$res = M('LiveRecordDetail')->where(array('id' => $record_id))->save(array(
					'live_push_size' => $live_push_size,
					'live_network_type' => $live_network_type,
					'update_time' => time(),
					'status' => 1,
				));

                $message['resultCode'] = 0;
                $message['msg'] = '更新成功';
                $this->ajaxReturn($message);
			} else {
	            $message['resultCode'] = 1;
	            $message['msg'] = '服务器异常';
	            $this->ajaxReturn($message);					
			}

		} else {
            $message['resultCode'] = 1;
            $message['msg'] = '未知ID';
            $this->ajaxReturn($message);			
		}
	}

	/**
	 * 直播开始记录
	 */
	public function addStartLiveRecord() {
		apigetpost();
		$live_id = I('post.id', 0);
		$live_network_type = I('post.live_network_type');

		if($live_id) {
			$res = M('LiveRecordDetail')->data(array(
				'live_id' => $live_id,
				'live_network_type' => $live_network_type,
				'update_time' => time(),
				'create_time' => time(),
			))->add();

			if($res) {
	 			$message['resultCode'] = 0;
	            $message['msg'] = '';
	            $message['rid'] = $res;
	            $this->ajaxReturn($message);					
			} else {
	            $message['resultCode'] = 1;
	            $message['msg'] = '服务器异常';
	            $this->ajaxReturn($message);					
			}

		} else {
 			$message['resultCode'] = 1;
            $message['msg'] = '未知ID';
            $this->ajaxReturn($message);			
		}
	}

	/**
	 * 草稿状态改为待审核状态
	 * @return [type] [description]
	 */
	public function updateDraftToWaitStatus() {
		apigetpost();
		$live_id = I('post.id', 0);	
		if($live_id) {
			$group_id = M('Live')->where(array('id' => $live_id))->getField('group_id');
			$res = M('Live')->where(array('group_id' => $group_id, 'v_status' => -1))->save(array(
				'v_status' => 0,
			));

			if($res !== false) {
	 			$message['resultCode'] = 0;
	            $message['msg'] = '修改成功';
	            $this->ajaxReturn($message);					
			} else {
	            $message['resultCode'] = 1;
	            $message['msg'] = '服务器异常';
	            $this->ajaxReturn($message);					
			}

		} else {
 			$message['resultCode'] = 1;
            $message['msg'] = '未知ID';
            $this->ajaxReturn($message);			
		}			
	}
}